import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
} from "react-native";
import { Stack } from "expo-router";
import { getHeaderStyle } from "@/styles/header.style";
import { useTheme } from "@/contexts/ThemeContext";
import styles from "./index.style";
import { AnimatedCircularProgress } from "react-native-circular-progress";
import * as FileSystem from "expo-file-system";
import useChatSessionStore from "@/store/chat-session";
import useChatMessageStore from "@/store/chat-message";
/**
 * 获取指定目录的大小
 * @param dirUri 目录URI
 * @returns 目录大小（字节）
 */
const getDirectorySize = async (dirUri: string) => {
  let totalSize = 0;
  const readDir = async (uri: string) => {
    const items = await FileSystem.readDirectoryAsync(uri);
    for (const item of items) {
      const itemUri = `${uri}/${item}`;
      const info = await FileSystem.getInfoAsync(itemUri);
      if (info.isDirectory) {
        await readDir(itemUri);
      } else {
        if (info.exists) {
          totalSize += info.size || 0;
        }
      }
    }
  };
  await readDir(dirUri);
  return totalSize;
};

/**
 * 格式化字节数为易读的字符串
 * @param bytes 字节数
 * @returns 格式化后的字符串
 */
const formatBytes = (bytes: number): string => {
  if (bytes >= 1024 * 1024 * 1024) {
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
  } else if (bytes >= 1024 * 1024) {
    return (bytes / (1024 * 1024)).toFixed(2) + " MB";
  } else if (bytes >= 1024) {
    return (bytes / 1024).toFixed(2) + " KB";
  } else {
    return bytes + " B";
  }
};

/**
 * 格式化百分比为字符串
 * @param value 百分比值
 * @returns 格式化后的百分比字符串
 */
const formatPercent = (value: number): string => {
  return value.toFixed(4) + "%";
};

export default function StorageSettings() {
  // 获取当前主题模式
  const { themeMode } = useTheme();
  // 获取基于当前主题的header样式
  const headerStyles = getHeaderStyle(themeMode);

  // app已使用存储空间
  const [usedSpace, setUsedSpace] = useState(0);
  // app已缓存空间
  const [cachedSpace, setCachedSpace] = useState(0);
  // app已使用总空间
  const [totalSpace, setTotalSpace] = useState(0);
  // app已使用空间占设备总空间的百分比
  const [usedPercent, setUsedPercent] = useState(0);
  // 是否正在加载数据
  const [isLoading, setLoading] = useState(true);

  const { clearSession } = useChatSessionStore().actions.async;
  const { clearAllMessages } = useChatMessageStore().actions.async;

  const clearCache = async () => {
    Alert.alert("清理缓存", "是否清理TeleChat的缓存数据？", [
      { text: "取消", style: "cancel" },
      {
        text: "清理",
        onPress: async () => {
          try {
            // 清理缓存目录
            await FileSystem.deleteAsync(FileSystem.cacheDirectory!, {
              idempotent: true,
            });
            setCachedSpace(0); // 重置缓存空间
            Alert.alert("清理成功", "TeleChat的缓存数据已清理。");
          } catch (error) {
            console.error("清理缓存失败:", error);
            Alert.alert("清理失败", "无法清理TeleChat的缓存数据，请稍后再试。");
          }
        },
        style: "destructive",
      },
    ]);
  };

  const deleteChatData = async () => {
    setLoading(true);
    await clearSession();
    //  await clearAllMessages();
    setLoading(false);
  };

  useEffect(() => {
    // 模拟数据加载
    const loadAppData = async () => {
      try {
        // 应用内部文件目录（DocumentDirectory + CacheDirectory）
        const docSize = await getDirectorySize(FileSystem.documentDirectory!);
        const cacheSize = await getDirectorySize(FileSystem.cacheDirectory!);
        const appUsedSize = docSize + cacheSize;
        // 获取设备总存储空间
        const deviceTotalSpace = await FileSystem.getTotalDiskCapacityAsync();
        // 计算应用已使用空间占设备总空间的百分比
        const appUsedPercent = deviceTotalSpace
          ? (appUsedSize / deviceTotalSpace) * 100
          : 0;

        setUsedPercent(appUsedPercent);
        setCachedSpace(cacheSize);
        setUsedSpace(docSize);
        setTotalSpace(appUsedSize);
      } catch (error) {
        console.error("加载数据失败:", error);
      } finally {
        setLoading(false);
      }
    };
    loadAppData();
  }, []);

  return (
    <>
      <Stack.Screen
        options={{
          title: "储存设置",
          headerTitleAlign: headerStyles.headerTitleAlign as "left" | "center",
          headerStyle: headerStyles.headerStyle,
          headerTintColor: headerStyles.headerTintColor,
          headerTitleStyle: headerStyles.headerTitleStyle,
        }}
      />
      <ScrollView style={styles.container}>
        {isLoading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color="#007BFF" />
            <Text style={styles.loadingText}>正在读取数据...</Text>
          </View>
        ) : (
          <>
            {/*圆环图*/}
            <View style={styles.chartContainer}>
              {/* 第一部分：TeleChat */}
              <AnimatedCircularProgress
                size={200}
                width={12}
                fill={usedPercent}
                tintColor="#FFA500"
                backgroundColor="#e6e6e6"
                rotation={0}
              >
                {() => (
                  <View style={styles.centerText}>
                    <Text style={styles.usedText}>TeleChat已使用</Text>
                    <Text style={styles.usedGB}>{formatBytes(totalSpace)}</Text>
                    <Text style={styles.percentText}>
                      占手机存储：{formatPercent(usedPercent)}
                    </Text>
                  </View>
                )}
              </AnimatedCircularProgress>
              {/* 图例 */}
              <View style={styles.legendContainer}>
                <View style={styles.legendItem}>
                  <View
                    style={[styles.legendDot, { backgroundColor: "#007BFF" }]}
                  />
                  <Text>TeleChat</Text>
                </View>
                <View style={styles.legendItem}>
                  <View
                    style={[styles.legendDot, { backgroundColor: "#B0B0B0" }]}
                  />
                  <Text>手机可用空间</Text>
                </View>
              </View>
            </View>

            {/*数据块1*/}
            <View style={styles.dataBlock}>
              <View>
                <View style={styles.dataHeader}>
                  <Text style={styles.dataTitle}>聊天与文件</Text>
                  <TouchableOpacity
                    style={[styles.button, { backgroundColor: "#FF6347" }]}
                    onPress={deleteChatData}
                  >
                    <Text style={[styles.buttonText, { color: "#fff" }]}>
                      删除
                    </Text>
                  </TouchableOpacity>
                </View>
                <Text style={styles.dataSubText}>{formatBytes(usedSpace)}</Text>
                <Text style={styles.dataDesc}>
                  包含聊天记录、文件以及下载的资源。
                </Text>
              </View>
            </View>

            {/*数据块2*/}
            <View style={styles.dataBlock}>
              <View>
                <View style={styles.dataHeader}>
                  <Text style={styles.dataTitle}>缓存数据</Text>
                  <TouchableOpacity
                    style={[styles.button, { backgroundColor: "#007BFF" }]}
                    onPress={clearCache}
                  >
                    <Text style={[styles.buttonText, { color: "#fff" }]}>
                      清理
                    </Text>
                  </TouchableOpacity>
                </View>
                <Text style={styles.dataSubText}>
                  {formatBytes(cachedSpace)}
                </Text>
                <Text style={styles.dataDesc}>
                  使用TeleChat产生的临时数据，清理不影响正常使用。
                </Text>
              </View>
            </View>

            {/*其他数据说明*/}
            <Text style={styles.footerNote}>
              <Text>
                包含TeleChat应用程序、其他账号的文件和聊天记录等，如需清理其他账号的内容，请切换账号。
              </Text>
            </Text>
          </>
        )}
      </ScrollView>
    </>
  );
}
